<?php


namespace app\api\controller\v33;


use app\aliyun\controller\AliyunFilterWord;
use app\api\controller\v2\Auth;
use app\common\cachemodel\ArticleComment;
use app\common\cachemodel\ArticleCommentReply;
use app\common\cachemodel\zl1_relation\Zl1AstrCommunityArticle;
use app\common\cachemodel\zl1_relation\Zl1AstrCommunityArticleZan;
use app\common\cachemodel\zl1_relation\Zl1RelationTag;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\Util;
use app\common\model\Recode;
use app\common\model\User;
use app\common\model\UserPush;
use think\Env;
use think\response\Json;
use XznsTools\cache\CacheManage;

class UserAstrCommunity extends Auth
{
    protected $inSignNames = [
        1 => '白羊座',
        2 => '金牛座',
        3 => '双子座',
        4 => '巨蟹座',
        5 => '狮子座',
        6 => '处女座',
        7 => '天秤座',
        8 => '天蝎座',
        9 => '射手座',
        10 => '摩羯座',
        11 => '水瓶座',
        12 => '双鱼座',
    ];

    /**
     * 发布星座讨论
     */
    public function createArticle()
    {
        $inSign = input('in_sign/d', 0);
        $relationId = input('relation_id/d', 0);
        $title = trim(input('title/s', ''));
        $photoListStr = input('photo_list/s', '');

        if (!in_array($inSign, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if (!$title)
        {
            return show(config('code.error'), '请输入讨论的内容');
        }

        if (mb_strlen($title) > 80)
        {
            return show(config('code.error'), '讨论的内容最多80字');
        }

        $photoList = json_decode($photoListStr, true);

        if (count($photoList) > 3)
        {
            return show(config('code.error'), '请求异常，最多插入三张图片～');
        }

        if ($this->user['no_comment'])
        {
            return show(202, '发布讨论失败，已被禁止发布讨论');
        }

        if (Util::commentCheck($this->user['id'], [
            'in_sign' => $inSign,
            'relation_id' => $relationId,
            'title' => $title,
        ],10))
        {
            return show(config('code.error'), '别心急等一等～');
        }

        if ($relationId !== 0)
        {
            $relationList = (new Zl1RelationTag())->getRelationTag(0);
            if (!isset($relationList[$relationId]))
            {   // 关系ID 错误
                return show(config('code.error'), '请求异常，请稍后再试～');
            }
        }

        //阿里云 验证【title内容及图片】
        $res = AliyunFilterWord::checkText($title, 'question_pic_check');
        if ($res)
        {
            return show(config('code.error'), '问题中有敏感词');
        }
        $ossHost = Env::get('host.photo');
        foreach ($photoList as $photo)
        {
            $res = AliyunFilterWord::checkImg(1, $ossHost . $photo, 'question_pic_check');
            if ($res['status'] === false)
            {
                return show(config('code.error'), '图片包含' . $res['text']);
            }
        }

        $data = [
            'uid' => $this->user['id'],
            'title' => $title,
            'photos' => $photoListStr,
            'in_sign' => $inSign,
            'relation_id' => $relationId,
            'in_sign_relation_id' => $inSign * 10000 + $relationId,
            'create_time' => $this->request->time()
        ];

        $id = (new Zl1AstrCommunityArticle())->SaveData($data);

        return show(config('code.success'), '请求成功', ['id' => $id]);
    }

    /**
     * 星座话题 评论或评论回复
     * @return Json
     */
    public function articleComment()
    {
        $id = input('id/d', 0);
        $type = input('type/d', 0);
        $content = trim(htmlspecialchars(input('content/s', '')));
        $pid = input('pid/d', 0);
        $uid = $this->user['id'];

        $n = $type === 1 ? '评论' : '评论回复';
        if ($content === '')
        {
            return show(config('code.error'), $n . '内容不能为空');
        }

        if (!$id)
        {
            return show(config('code.error'), '请求异常');
        }

        if ($this->user['no_comment'])
        {
            return show(config('code.error'), $n . '失败，已被禁止' . $n);
        }
        $adorn = Util::getUserAdorn($this->user['id']);

        if ($type === 1)
        {
            $astrCommunityArticleModel = new Zl1AstrCommunityArticle();
            $articleDetail = $astrCommunityArticleModel->getInfoById($id, ['read_num', 'comment_num']);
            if (!$articleDetail)
            {
                return show(config('code.error'), '星座讨论内容不存在～');
            }

            $data = [
                'aid' => $id,
                'uid' => $uid,
                'content' => $content,
                'type' => 5,    //类型 1=>星文评论，2=>女神动态评论，3=>女神专区评论 必传 5=>星座讨论
                'status' => 0   // 状态 0 正常 -1 删除
            ];
            $res = (new ArticleComment())->commentAdd($this->user, $data);

            if ($res['status'])
            {
                // 阅读数 新增
                $astrCommunityArticleModel->changeArticleInfo([
                    'id' => $id,
                    'read_num' => $articleDetail['read_num'],
                    'comment_num' => $articleDetail['comment_num'],
                ], 2, 1);

                $rData = [
                    'id' => $res['id'],
                    'avatar' => $this->user['avatar'],
                    'nickname' => $this->user['nickname'],
                    'time' => '刚刚',
                    'create_time' => '刚刚',
                    'content' => htmlspecialchars_decode($content),
                    'reply_num' => 0,
                    'good_num' => 0,
                    'is_good' => 0,
                    'vip' => (new ZlUserVip())->getUserVipLevel($this->user['id']),
                    'is_owner' => 1,
                    'reply_list' => []
                ];
                $rData = array_merge($rData, $adorn);
                return show(config('code.success'), '评论成功', $rData);
            }
            return show(config('code.error'), $res['msg']);
        } else
        {
            // 评论详情
            $commentInfo = current((new ArticleComment())->batchGetInfo([$id], ['uid']));
            if (!$commentInfo)
            {
                return show(config('code.error'), '数据不存在');
            }

            // 判断 用户是否允许回复他
            if ($pid)
            {   // 回复->评论回复
                // 获取回复的 评论回复用户uid
                $replyUid = (new ArticleCommentReply())->getInfoById($pid, ['uid1']);
                if ($replyUid['uid1'] != $this->user['id'])
                {   // 不是回复自己
                    $replyStatus = (new UserPush())->getUserReplyStatus((int)$replyUid['uid1']); // 是否允许回复自己 true 允许 false 不允许
                    if (!$replyStatus)
                    {   // 不允许回复
                        return show(config('code.error'), '对方关闭了评论回复');
                    }
                }
            } else
            {   // 回复评论
                if ($commentInfo['uid'] != $this->user['id'])
                {   // 不是自己评论自己事
                    $replyStatus = (new UserPush())->getUserReplyStatus((int)$commentInfo['uid']); // 是否允许回复自己 true 允许 false 不允许
                    if (!$replyStatus)
                    {   // 不允许回复
                        return show(config('code.error'), '对方关闭了评论回复');
                    }
                }
            }

            $data = [
                'comment_id' => $id,
                'pid' => $pid,
                'content' => $content,
                'uid' => (int)$this->user['id'],
                'status' => 0   // 状态 0 正常 -1 删除
            ];

            $res = (new ArticleCommentReply())->addCommentReply($this->user, $data);

            if ($res['status'])
            {
                $rData = [
                    'id' => $res['id'],
                    'avatar' => $this->user['avatar'],
                    'nickname1' => $this->user['nickname'],
                    'nickname2' => $pid ? $res['nickname2'] : null,
                    'time' => '刚刚',
                    'create_time' => '刚刚',
                    'content' => htmlspecialchars_decode($content),
                    'content_type' => 1,
                    'good_num' => 0,
                    'is_good' => 0,
                    'is_owner' => 1,
                    'vip' => (new ZlUserVip())->getUserVipLevel($this->user['id']),
                ];
                $rData = array_merge($rData, $adorn);
                return show(config('code.success'), '评论成功', $rData);
            }

            return show(config('code.error'), $res['msg']);
        }
    }

    /**
     * 星座讨论 赞同与反对
     */
    public function articleZan()
    {
        $id = input('id/d', 0);
        $type = input('type/d', 0); // 0=>不赞同不反对 1=>赞同 2=>反对

        if (!$id)
        {
            return show(config('code.error'), '请求异常');
        }
        //验证是否重复操作
        if (Util::commentCheck($this->user['id'], ['id' => $id, 'type' => $type]))
        {
            return show(config('code.error'), '别心急，等一等');
        }

        $astrCommunityArticleModel = new Zl1AstrCommunityArticle();

        $articleDetail = $astrCommunityArticleModel->getInfoById($id, ['zan_num', 'zan_num2']);

        if (!$articleDetail)
        {
            return show(config('code.error'), '服务异常，讨论不存在～');
        }

        $astrCommunityArticleZanModel = new Zl1AstrCommunityArticleZan();

        $zanData = $astrCommunityArticleZanModel->getZan($this->user['id'], [$id]);

        $oldZan = (int)(empty($zanData) ? 0 : $zanData);
        if ($type === $oldZan)
        {
            return show(config('code.success'), '操作成功', $articleDetail);
        }

        $d = [];
        if ($oldZan === 1)
        {
            $d['zan_num'] = $articleDetail['zan_num'] - 1;
            $articleDetail['zan_num'] = $articleDetail['zan_num'] - 1;
        }
        if ($oldZan === 2)
        {
            $d['zan_num2'] = $articleDetail['zan_num2'] - 1;
            $articleDetail['zan_num2'] = $articleDetail['zan_num2'] - 1;
        }
        if ($type === 1)
        {
            $d['zan_num'] = $articleDetail['zan_num'] + 1;
            $articleDetail['zan_num'] = $articleDetail['zan_num'] + 1;
        }
        if ($type === 2)
        {
            $d['zan_num2'] = $articleDetail['zan_num2'] + 1;
            $articleDetail['zan_num2'] = $articleDetail['zan_num2'] + 1;
        }

        $astrCommunityArticleZanModel->setZan($this->user['id'], $id, $type);

        $astrCommunityArticleModel->UpdateData($id, $d);

        return show(config('code.success'), '操作成功', $articleDetail);
    }

    /**
     * 个人主页
     */
    public function communityHome()
    {
        $page = input('page/d', 1);

        if ($page < 1)
        {
            $page = 1;
        }
        $astrCommunityArticleModel = new Zl1AstrCommunityArticle();
        // 获取装饰信息
        $adorn = Util::getUserAdorn($this->user['id']);

        $pageData = $astrCommunityArticleModel->getUserArticleIds($this->user['id'], $page, 10);

        $userDes = '小行星神秘人';
        $address = '';
        $introTag = '';
        if ($this->user['rid'])
        {
            $recode = (new Recode())->getRecode(['id' => $this->user['rid']]);
            if ($recode)
            {
                $utilModel = new Util();
                $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);
                $address = str_replace(['省', '市'], '', $recode['live_country']);
//                $address = rtrim(rtrim($recode['live_country'], '市'), '省');

                $introTag = mb_substr($recode['year'], 2, 1) . '0后';

                $sex = $recode['type'] ?? 0;
            }
        }

        $ids = array_keys($pageData['data']);
        if ($ids)
        {
            $relationList = (new Zl1RelationTag())->getRelationTag(0, ['id', 'name']);

            $datas = $astrCommunityArticleModel->batchGetInfoByIds($ids, []);

            $astrCommunityArticleZanModel = new Zl1AstrCommunityArticleZan();

            $zanData = $astrCommunityArticleZanModel->getZan($this->user['id'], $ids);

            if ($zanData)
            {
                if (count($ids) === 1 && !is_array($zanData))
                {
                    $zanData = [current($ids) => (int)$zanData];
                }
            }

            $resData = [];
            foreach ($pageData['data'] as $id => $i)
            {
                $d = $datas[$id];
                $resData[] = [
                    'id' => $d['id'],
                    'nickname' => $this->user['nickname'],
                    'avatar' => $this->user['avatar'],
                    'create_time' => Util::timeToStr($d['create_time']),
                    'user_des' => $userDes,
                    'title' => $d['title'],
                    'comment_num' => $d['comment_num'],
                    'photo_list' => $d['photos'],
                    'isself' => 1,
                    'avatar_adorn' => $adorn['avatar_adorn'],
                    'tag' => $adorn['tag'],
                    'badge' => $adorn['badge'],
                    'sign_name' => $this->inSignNames[$d['in_sign']],
                    'relation_name' => $d['relation_id'] > 0 ? $relationList[$d['relation_id']]['name'] : '',
                    'zan_num' => $d['zan_num'],
                    'zan_num2' => $d['zan_num2'],
                    'is_zan' => isset($zanData[$id]) && $zanData[$id] ? (int)$zanData[$id] : 0,
                ];
            }

            $pageData['data'] = $resData;
        }

        $resData = [
            'nickname' => $this->user['nickname'],
            'avatar' => $this->user['avatar'],
            'avatar_adorn' => $adorn['avatar_adorn'],
            'user_des' => $userDes,
            'tag' => $adorn['tag'],
            'badge' => $adorn['badge'],
            'address' => $address,
            'intro_tag' => $introTag,
            'sex' => $sex ?? 0,
            'list' => $pageData
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 删除星座讨论
     */
    public function delArticle()
    {
        $id = input('id/d', 0);
        if (!$id)
        {
            return show(config('code.error'), '请求异常');
        }

        $astrCommunityArticleModel = new Zl1AstrCommunityArticle();

        $articleDetail = $astrCommunityArticleModel->getInfoById($id, ['uid', 'status']);

        if (!$articleDetail || $articleDetail['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '讨论存在，删除失败～');
        }

        if ($articleDetail['status'] === -1)
        {
            CacheManage::getInstance()->setCacheConfig('astr_community.article')
                ->setCacheKeyDetail('user_list', $this->user['id'])
                ->delJudge($id, 'user_list');
            return show(config('code.success'), '讨论删除成功');
        }

        $astrCommunityArticleModel->UpdateData($id, ['status' => -1]);

        CacheManage::getInstance()->setCacheConfig('astr_community.article')
            ->setCacheKeyDetail('user_list', $this->user['id'])
            ->delJudge($id, 'user_list');

        return show(config('code.success'), '讨论删除成功');
    }
}
